﻿using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace Boxie
{
    public partial class frmSmartTyping : Form
    {
        private const int WM_SETREDRAW = 0x000B;
        private const int WM_USER = 0x400;
        private const int EM_GETEVENTMASK = (WM_USER + 59);
        private const int EM_SETEVENTMASK = (WM_USER + 69);
        [DllImport("user32", CharSet = CharSet.Auto)]
        private extern static IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, IntPtr lParam);
        private IntPtr eventMask = IntPtr.Zero;
        public int cmdCount;

        public RichTextBox txt;

        public frmSmartTyping()
        {
            InitializeComponent();
            txt = rtb;
            if (BoxieRegLib.GetSettingBool("General/WindowTopMost", true))
                this.TopMost = true;
        }

        private void frmSmartTyping_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        public void RepositionWindow(frmBoxie b)
        {
            this.Left = b.Left;
            this.Top = b.Top - this.Height - 10;
        }

        private void rtb_TextChanged(object sender, EventArgs e)
        {
            SetWindowHeight();
        }

        public void SetWindowHeight()
        {
            rtb.Height = Convert.ToInt32((1.5 * rtb.Font.Height)) + rtb.GetPositionFromCharIndex(rtb.TextLength - 1).Y;
            this.Height = 5 + rtb.Height;
        }

        public void lockRtb(bool locknow)
        {
            if (locknow)
            {
                // Stop redrawing:
                SendMessage(rtb.Handle, WM_SETREDRAW, 0, IntPtr.Zero);
                // Stop sending of events:
                eventMask = SendMessage(rtb.Handle, EM_GETEVENTMASK, 0, IntPtr.Zero);
            }
            else
            {
                // turn on events
                SendMessage(rtb.Handle, EM_SETEVENTMASK, 0, eventMask);
                // turn on redrawing
                SendMessage(rtb.Handle, WM_SETREDRAW, 1, IntPtr.Zero);
            }
        }

        public void autoComplete(TextBox txt)
        {
            if (this.cmdCount != 1)
                return;
            string[] sections = txt.Text.Split(' ');
            txt.Text = "";
            for (int i = 0; i < sections.GetUpperBound(0); i++)
                txt.Text += sections[i] + " ";
            txt.Text += rtb.Tag;
            txt.SelectionStart = txt.TextLength;
        }
    }
}
